<script setup>
import {computed, ref} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {uploadImage} from "@/api/upload";
const fileList = ref([]);
const maxSize = 20 * 1024 * 1024;
const props = defineProps({
  imageUrl: {
    type: String,
    default: ''
  },
  required: {
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['update:imageUrl'])
const uploadImageUrl = computed({
  get() {
    return props.imageUrl
  },
  set(val) {
    emit('update:imageUrl', val)
  }
})

// 上传前校验
const beforeRead = (file) => {
  if (!/image\/\w+/.test(file.type)) {
    showFailToast('请选择图片文件');
    return false;
  }
  if (file.size > maxSize) {
    showFailToast(`文件大小不能超过20MB`);
    return false;
  }
  return true;
};
// 上传图片
const afterRead = async (file) => {
  try {
    const data = new FormData();// 创建form对象
    data.append('file', file.file);// 通过append向form对象添加数据
    const result = await uploadImage(data);// 异步上传图片
    if (result.msg !== '请求成功') {
      showFailToast('上传失败，请重试');
      return;
    }
    const imageUrl = result.data.uploadUrl || '';// 获取图片地址
    if (!imageUrl || imageUrl === '') {
      showFailToast('图片地址出现问题，请重试');
      return;
    }
    uploadImageUrl.value= imageUrl;// 将图片地址赋值给表单
    showSuccessToast('上传成功');
  } catch (error) {
    console.log(error, '<<<-----error')
    uploadImageUrl.value = '';// 清空图片地址
    fileList.value = [];// 清空上传图片列表
    showFailToast('上传失败，请重试');
  }
};
const deleteFile = () => {
  uploadImageUrl.value = '';// 清空图片地址
  fileList.value = [];// 清空上传图片列表
}
</script>
<template>
  <van-field label="上传图片" :required="required">
    <template #input>
      <van-uploader
          v-model="fileList"
          :before-read="beforeRead"
          :max-size="maxSize"
          :max-count="1"
          accept="image/*"
          :deletable="true"
          :after-read="afterRead"
          @delete="deleteFile"
      >
        <template #preview-cover="{ file }">
          <div class="preview-cover van-ellipsis">{{ file.name }}</div>
        </template>
      </van-uploader>
    </template>
  </van-field>
</template>

<style scoped>
.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  border-radius: 12px;
  background: rgba(0, 0, 0, 0.3);
}
</style>
